<script setup lang="ts">
import { addObj, putObj } from '/@/api/common';
import { useMessage } from '/@/hooks/message';

const emit = defineEmits(['refresh']);
const props = defineProps<{ rule: object }>();
const statLoading = ref(false);

const visible = ref(false);
const form = ref({
	id: '',
});
const flag = ref(false);

// const rule = ref([]);

const options = ref({
	onSubmit: (formData) => {
		statLoading.value = true;
		if (formData.id ===undefined || formData.id === '') {
			addObj(form.value.label, formData).then(()=>{
				statLoading.value = false;
				emit('refresh');
				visible.value = false;
			}).catch(err=>{
				useMessage().error(err.msg)
			})
		} else {
			putObj(form.value.label, formData).then(()=>{
				statLoading.value = false;
				emit('refresh');
				visible.value = false;
			})
		}

	},
	resetBtn: flag.value,
});
// 打开弹窗
const openDialog = (label: string, row: object) => {
	if (props.rule === undefined||props.rule === null|| props.rule === '') {
		useMessage().error("未配置表单")
		return;
	}
	visible.value = true;
	form.value = row;
	form.value.label = label;
	options.value.resetBtn = !row.id;
};
const cleanData = () => {
	Object.keys(form.value).forEach((key: string) => {
		form.value[key] = '';
	});
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<template>
	<el-dialog  @close="cleanData" :title="form.id ? '编辑' : '新增'" v-model="visible" :close-on-click-modal="false" draggable>
		<form-create v-loading="statLoading" :rule="rule" v-model="form" :option="options" />
	</el-dialog>
</template>

<style scoped lang="scss"></style>
